﻿using Dtmcli;
using Microsoft.AspNetCore.Mvc;
using MQCommon;
using MQCommon.SagaModel;
using MySqlConnector;
using SagaUser.Model;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SagaUser.Controllers
{
    [ApiController]
    [Route("/api")]
    [ApiExplorerSettings(IgnoreApi = true)]
    public class UserPayController : ControllerBase
    {
        private readonly IBranchBarrierFactory _barrierFactory;
        private readonly ILogger<UserPayController> _logger;
        public UserPayController(ILogger<UserPayController> logger, IBranchBarrierFactory barrierFactory)
        {
            _logger = logger;
            _barrierFactory = barrierFactory;
        }
        // GET: api/<UserPayController>
        [HttpPost("ctreatUser")]
        public async Task<ActionResult> ctreatUser( [FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op,[FromBody] OrderModel body)
        {
            DapperHelper dh = new DapperHelper();
            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            using (var connection = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(connection, async (tx) =>
                {
                    var UserMoneys = dh.Query<UserMoney>($"select *  from User_Money where id={body.UserId}");
                    var money = UserMoneys[0].money - body.Money;
                    dh.Execute($"update User_Money set money={money},updatetime='{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}' where id={body.UserId}");
                    dh.Execute($"insert into User_Accounts values(null,{body.BusinessID},{body.UserId},{body.Money},'koukuan',{UserMoneys[0].money},'{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}')");
                    await Task.CompletedTask;
                });
            }
            return Ok(TransResponse.BuildSucceedResponse());
        }
        [HttpPost("ctreatUsererror")]
        public async Task<ActionResult> ctreatUsererror([FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {
            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            await dh.DTMTransactionAsync(() => {
            //回滚或者补偿
            }, branchBarrier);
            return Ok(TransResponse.BuildSucceedResponse());
        }
        [HttpPost("ctreatUsererrorOne")]
        public async Task<ActionResult> ctreatUsererrorOne([FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {
            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            throw new NotImplementedException();
            await dh.DTMTransactionAsync(() => {
                //回滚或者补偿
            }, branchBarrier);
            return Ok(TransResponse.BuildSucceedResponse());
        }
        [HttpPost("ctreatUserOne")]
        public async Task<ActionResult> ctreatUserOne([FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {
            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            using (var connection = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(connection, async (tx) =>
                {
                    var UserMoneys = dh.Query<UserMoney>($"select *  from User_Money where id={body.UserId}");
                    var money = UserMoneys[0].money - body.Money;
                    dh.Execute($"update User_Money set money={money},updatetime='{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}' where id={body.UserId}");
                    dh.Execute($"insert into User_Accounts values(null,{body.BusinessID},{body.UserId},{body.Money},'koukuan',{UserMoneys[0].money},'{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}')");
                    await Task.CompletedTask;
                });
            }

            return Ok(TransResponse.BuildSucceedResponse());
        }
        [HttpPost("ctreatUserTwo")]
        public async Task<ActionResult> ctreatUserTwo([FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {
            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            using (var connection = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(connection, async (tx) =>
                {
                    var UserMoneys = dh.Query<UserMoney>($"select *  from User_Money where id={body.UserId}");
                    var money = UserMoneys[0].money - body.Money;
                    dh.Execute($"update User_Money set money={money},updatetime='{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}' where id={body.UserId}");
                    dh.Execute($"insert into User_Accounts values(null,{body.BusinessID},{body.UserId},{body.Money},'koukuan',{UserMoneys[0].money},'{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}')");
                    await Task.CompletedTask;
                });
            }

            return Ok(TransResponse.BuildSucceedResponse());
        }
    }
}
